package com.his.core;

import com.alipay.api.internal.util.file.IOUtils;
import com.his.utils.RsaUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import java.io.IOException;
import java.io.InputStream;

/**
 * 自定义的http消息类
 */
public class MyHttpInputMessage implements HttpInputMessage {

    private final HttpHeaders headers;
    private final InputStream body;
    public MyHttpInputMessage(HttpInputMessage inputMessage) throws Exception {
        this.headers = inputMessage.getHeaders();
        //拿到body中的数据
        String content = easpString(IOUtils.toString(inputMessage.getBody(),"utf-8"));
        //执行解密,将数据放到body中
        this.body = IOUtils.toInputStream(RsaUtils.decrypt(content));
    }

    @Override
    public InputStream getBody() throws IOException {
        return body;
    }

    @Override
    public HttpHeaders getHeaders() {
        return headers;
    }

    /**
     *获取body中的加密数据
     * @param requestData
     * @return
     */
    public String easpString(String requestData){
        if(requestData != null && !requestData.equals("")){
            String s = "{\"requestData\":";
            if(!requestData.startsWith(s)){
                throw new RuntimeException("参数【requestData】缺失异常！");
            }else{
                int closeLen = requestData.length()-1;
                int openLen = "{\"requestData\":".length();
                return StringUtils.substring(requestData, openLen, closeLen);
            }
        }
        return "";
    }
}
